﻿using BaseUi.ViewModels;
using BaseUi.Views.MainWindows;
using HandyControl.Controls;
using Newtonsoft.Json;
using Ping9719.DeviceCommunication.Clients.PLC;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;

namespace BaseUi.ViewModel
{
    public class MainViewModel : BindableBase
    {
        private SolidColorBrush anquanColor = MainWindow4.ytosafe;
        private string anquanCont = "";

        public string anquancont { get => anquanCont; set { SetProperty(ref anquanCont, value); } }
        public SolidColorBrush anquancolor { get => anquanColor; set { SetProperty(ref anquanColor, value); } }
        public CommonViewModel CommonViewModel = new CommonViewModel();
        Mutex mutex;
        private string title = string.Empty;
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get => title; set { SetProperty(ref title, value); } }

        #region 专用_MainWindow2
        //隐藏式选项卡的高度
        public double TabItemHeight { get; set; } = 0;

        private string SelectedValue_ = "主页";
        public string SelectedValue { get => SelectedValue_; set { SetProperty(ref SelectedValue_, value); } }
        #endregion

        private DateTime time;
        /// <summary>
        /// 时间
        /// </summary>
        public DateTime Time { get => time; set { SetProperty(ref time, value); } }
        /// <summary>
        /// 在初始化前的相关检查
        /// </summary>
        public bool InitAgo()
        {
            //只允许打开一个
            mutex = new Mutex(true, string.Concat("MengXunBaseUi", Path.GetFileNameWithoutExtension(LocalFile.AppName)), out bool createdNew);
            if (!createdNew)
            {
                MessageBox.Warning("已有实列在运行！", "提示");
                return false;
            }

            //初始化
            Tuple<string, string, Action>[] tuples = new Tuple<string, string, Action>[]
            {
                new Tuple<string, string, Action>("检测文件..", "缺少文件，尝试将项目[data/]中的所有文件复制到[bin/data/]中", () =>
                {
                    if(!System.IO.File.Exists(LocalFile.ConfigPath)||!System.IO.File.Exists(LocalFile.PlcDotPath))
                        throw new Exception("缺少文件，请尝试将项目[data/]中的所有文件复制到[bin/data/]中");
                }),
                new Tuple<string, string, Action>("检测文件..", "配置文件中没有内容，请联系管理员", () =>
                {
                    if(string.IsNullOrWhiteSpace(System.IO.File.ReadAllText(LocalFile.ConfigPath, Encoding.UTF8)))
                        throw new Exception($"配置文件[{LocalFile.ConfigPath}]中没有内容");
                }),
                new Tuple<string, string, Action>("初始化数据中..", "初始化数据库失败，请联系管理员", () =>
                {
                    AuthDb.Ini();
                    //WarnInfoDb.Ini();
                }),
                        new Tuple<string, string, Action>("连接PLC中..", "PLC连接失败，请检查网络", () =>
                {
                    LocalStatic.Plc = new HuiChuanClient(LocalFile.Config.Plc.Address,LocalFile.Config.Plc.Port);
                    var aaa= LocalStatic.Plc.Open();
                    //if (aaa.IsSucceed)
                    //{
                    //    PlcColor=true;
                    //}
                    //else
                    //{
                    //    PlcColor=false;
                    //}

                }),
                //new Tuple<string, string, Action>("连接PLC中..", "PLC连接失败，请检查网络", () =>
                //{
                //    var ipPort = LocalFile.Config.Plc.ToIpPort();
                //    //LocalStatic.Plc = new SiemensS7Client(SiemensVersion.S7_1200,ipPort.Address,ipPort.Port);
                //    //var res=LocalStatic.Plc.Open();
                //    //if (!res.IsSucceed)
                //    //    throw new Exception(res.Err);
                //}),
            };

            MainLoadWindow.TaskSleepTime = 200;
            if (!MainLoadWindow.Show(tuples))
                return false;

            //清理日志
            Task.Run(() =>
            {
                if (LocalFile.Config.Sys.SaveLogDay < 0)
                    return;

                Logs.Clear(TimeSpan.FromDays(LocalFile.Config.Sys.SaveLogDay));
                //WarnInfoDb.Clear(TimeSpan.FromDays(LocalFile.Config.Sys.SaveLogDay));
            });

            //json转换器
            {
                //JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                //{
                //    Converters = new[] { new JsonDateTimeConverter() },
                //};
            }

            //不登录，直接使用最高权限
            {
                UserLoginView.NotLogin();
                return true;
            }
            //登录
            {
                //var userLoginView = new UserLoginView();
                //var isok = userLoginView.ShowDialog() == true;
                //userLoginView = null;
                //return isok;
            }
        }

        /// <summary>
        /// 初始化并运行时间
        /// </summary>
        public async void Init(System.Windows.Window window)
        {
            //加载 程序名称
            var versionInfo = FileVersionInfo.GetVersionInfo(LocalFile.AppPath);
            //Title = versionInfo.ProductName;
            Title = "智能锡膏存储设备";

            //加载 窗体模式
            if (LocalFile.Config.Sys.StartupFull)
                window.WindowState = System.Windows.WindowState.Maximized;

            //注册 设备
            IotDevice.UserChange = ((iot) =>
            {
                if (string.IsNullOrEmpty(iot.Funct))
                    Growl.Info($"你点击了[{iot.Name}]，尝试改为[{iot.Val}]");
                else
                    Growl.Info($"你点击了[{iot.Name}][{iot.Funct}]，尝试改为[{iot.Val}]");

                Logs.Write(iot, LogsType.DeviceHand);
            });

            //注册 信息
            TextBoxLog.TextBoxLogAdd = ((info) =>
            {
                Logs.Write(info.Text, LogsType.Info, info.Time);
            });

            //加载 时钟
            while (true)
            {
                Time = DateTime.Now;
                await Task.Delay(1);
            }
        }

        public ICommand OpenUserCommand { get => new DelegateCommand(OpenUser); }
        /// <summary>
        /// 打开用户
        /// </summary>
        public void OpenUser()
        {
            if (UserInfoView.viewModel.IsLogin)
            {
                var userInfoView = new UserInfoView();
                userInfoView.ShowDialog();

                if (userInfoView.IsExitLogin)
                {
                    Growl.Info("您已退出登录。");
                    userInfoView = null;
                }
            }
            else
            {
                var userLoginView = new UserLoginView();

                //登录成功
                if (userLoginView.ShowDialog() == true)
                {
                    Growl.Success($"欢迎您：{UserInfoView.viewModel.LoginName}");
                    userLoginView = null;
                }
            }
        }

        public ICommand OpenLogCommand { get => new DelegateCommand(OpenLog); }
        /// <summary>
        /// 打开日记
        /// </summary>
        public void OpenLog()
        {
            if (!System.IO.Directory.Exists(LocalFile.LogDir))
            {
                Growl.Info("暂时没有日志。");
                return;
            }

            try
            {
                Folder.OpenFolder(LocalFile.LogDir);
            }
            catch (Exception)
            {
                Growl.Error("打开日志目录失败。");
            }
        }

        public ICommand OpenHelpCommand { get => new DelegateCommand(OpenHelp); }
        /// <summary>
        /// 打开帮助
        /// </summary>
        public void OpenHelp()
        {
            if (!System.IO.File.Exists(LocalFile.DocPath))
            {
                Growl.Info("帮助文档正在书写中。");
                return;
            }

            try
            {
                Folder.OpenFolderAndSelectedFile(LocalFile.DocPath);
            }
            catch (Exception)
            {
                Growl.Error("打开帮助文档失败。");
            }
        }

        public ICommand OpenWeCommand { get => new DelegateCommand(OpenWe); }
        /// <summary>
        /// 打开关于
        /// </summary>
        public void OpenWe()
        {
            var aboutView = new AboutView();
            aboutView.ShowDialog();
            aboutView = null;
        }
    }
}
